﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using RealtorsPortal.Business_Logic_Layer;
using System.Data;
using RealtorsPortal.Data_Access_Layer;
using RealtorsPortal.Entities;
using System.Web.SessionState;
using System.Collections;
using System.Globalization;
using System.Threading;

namespace RealtorsPortal.AdminCP
{
    public partial class PostAdvertisement : System.Web.UI.Page
    {
        CountriesDAL countriesDalObj = new CountriesDAL();
        RegionDAL regionDalObj = new RegionDAL();
        CitiesDAL citiesDalObj = new CitiesDAL();
        DistrictsDAL districtsDalObj = new DistrictsDAL();
        CategoriesDAL cateDalObj = new CategoriesDAL();
        AdvertisementsDAL adverDalObj = new AdvertisementsDAL();
        ParkagesDAL parkDalObj = new ParkagesDAL();
        AdvertisementsDAO advObj = new AdvertisementsDAO();
        AdsImages adsImageObj = new AdsImages();
        AdsImagesDAL adsDalObj = new AdsImagesDAL();
        string[] strUrl;
        int n = 0;
        int numImage = 0;
        int month;
        int year;
        int day;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    getCountries();
                    GetPackages();
                    getCategories();
                    ddlCountry.Items.Insert(0, "--Select Country--");
                    ddlPackages.Items.Insert(0, "--Select Package--");
                    ddlCategory.Items.Insert(0, "--Select Category--");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

        }

        private void HideDivForLand()
        {
            floor.Visible = false;
            BathAndBedroom.Visible = false;
            Amenity.Visible = false;
        }

        private void ShowDivForHouseAndVillage()
        {
            floor.Visible = true;
            BathAndBedroom.Visible = true;
            Amenity.Visible = true;
        }

        protected void btnPost_Click(object sender, EventArgs e)
        {

            bool chk = uploadAImage(); 
            if (chk)
            {
                UploadMultiFile();
            }
            else {
                return;
            }
            advObj.CategoryId = int.Parse(ddlCategory.SelectedValue);
            advObj.UserId = GetCurrentSession();
            advObj.DistrictId = int.Parse(ddlDistrict.SelectedValue);
            advObj.ParkageId = int.Parse(ddlPackages.SelectedValue);
            advObj.Title = txtTitle.Text;
            //if (rdbBuy.Checked)
            //{
            //    advObj.Type = "Buy";
            //}
            //else 
            if (rdbRent.Checked)
            {
                advObj.Type = "Rent";
            }
            else
            {
                advObj.Type = "Sell";
            }
            //advObj.ImageUrl = Server.MapPath("~\\Single Upload") + "\\" + SingleUpload.FileName;  //"..\\Images Upload" + "\\" + SingleUpload.FileName
            advObj.ImageUrl = "Single Upload" + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + SingleUpload.FileName;
            advObj.Price = txtPrice.Text;
            advObj.PostedDate = GetCurrentDate().ToString("MM-dd-yyyy");

            DateTime dt = Convert.ToDateTime(GetCurrentDate().ToString()); // DateTime.ParseExact(GetCurrentDate().ToString(), "MM-dd-yyyy", provider);
            if (dt.Month == 1 || dt.Month == 3||dt.Month == 5||dt.Month == 7||dt.Month == 8||dt.Month == 10||dt.Month == 12)
            {
                if (dt.Day + GetDurationOfPackage() > 31)
                {
                    day = dt.Day + GetDurationOfPackage() - 31;
                    month = (dt.Month + 1);
                    if (month > 12)
                    {
                        month = 1;
                        year = dt.Year + 1;
                    }
                    else {
                        year = dt.Year;
                    }
                }
                else {
                    day = dt.Day + GetDurationOfPackage();
                    month = dt.Month;
                    year = dt.Year;
                }
            }
            else if (dt.Month == 4 || dt.Month == 6 || dt.Month == 9 || dt.Month == 11)
            {
                if (dt.Day + GetDurationOfPackage() > 30)
                {
                    day = dt.Day + GetDurationOfPackage() - 30;
                    month = (dt.Month + 1);
                    if (month > 12)
                    {
                        month = 1;
                        year = dt.Year + 1;
                    }
                    else
                    {
                        year = dt.Year;
                    }
                }
                else
                {
                    day = dt.Day + GetDurationOfPackage();
                    month = dt.Month;
                    year = dt.Year;
                }
            }
            else if(dt.Month ==2){
                if (dt.Year % 400 == 0)
                {
                    if (dt.Day + GetDurationOfPackage() > 29)
                    {
                        day = dt.Day + GetDurationOfPackage() - 29;
                        month = (dt.Month + 1);
                        if (month > 12)
                        {
                            month = 1;
                            year = dt.Year + 1;
                        }
                        else
                        {
                            year = dt.Year;
                        }
                    }
                    else
                    {
                        day = dt.Day + GetDurationOfPackage();
                        month = dt.Month;
                        year = dt.Year;
                    }
                }
                else {
                    if (dt.Day + GetDurationOfPackage() > 28)
                    {
                        day = dt.Day + GetDurationOfPackage() - 28;
                        month = (dt.Month + 1);
                        if (month > 12)
                        {
                            month = 1;
                            year = dt.Year + 1;
                        }
                        else
                        {
                            year = dt.Year;
                        }
                    }
                    else
                    {
                        day = dt.Day + GetDurationOfPackage();
                        month = dt.Month;
                        year = dt.Year;
                    }
                }
            }
            advObj.ExpDate = (month + "-" + day + "-" + year).ToString();
            advObj.LandArea = float.Parse(TextBox1.Text);
            if (ddlCategory.SelectedItem.Text != "Land")
            {
                
                advObj.Floor = int.Parse(TextBox2.Text);
                advObj.Bedroom = int.Parse(TextBox4.Text);
                advObj.Bathroom = int.Parse(TextBox3.Text);
                advObj.Amenities = TextBox6.Text;
                advObj.BuiltYear = int.Parse(TextBox5.Text);
            }
            else {
                advObj.Floor = 0;
                advObj.Bedroom = 0;
                advObj.Bathroom = 0;
                advObj.Amenities = "";
                advObj.BuiltYear = 0;
            }
            advObj.Address = txtAddress.Text;
            advObj.Description = TextBox7.Text;
            advObj.IsFeatured = false;
            advObj.IsActive = true;

            int result = adverDalObj.InsertAvertisements(advObj);
            
            if (result > 0)
            {
                adsImageObj.AdvId = adsDalObj.GetNextID();
                InsertMultiImages();
                InsertToSubscription();
                string message = "Congratulation! Your Advertise is posted successful!";
                string url = "PayAdvertisement.aspx";
                Utilities.ShowAndRedirect(message,url);
            }
            else {
                string message = "Sorry! There is an error in posting, please contact to admin!";
                string url = "PostAdvertisement.aspx";
                Utilities.ShowAndRedirect(message, url);
            }
        }

        public bool Show(string message)
        {
            // Cleans the message to allow single quotation marks
            string cleanMessage = message.Replace("'", "\\'");
            string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

            // Gets the executing web page
            Page page = HttpContext.Current.CurrentHandler as Page;

            // Checks if the handler is a Page and that the script isn't allready on the Page
            if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
            {
                page.ClientScript.RegisterClientScriptBlock(typeof(Utilities), "alert", script);
            }
            return true;
        }

        private void InsertMultiImages() 
        {
            for (int i = 1; i < strUrl.Length; i++ )
            {
                adsImageObj.ImageUrl = strUrl[i].ToString();
                adsDalObj.InsertIntoAdsImage(adsImageObj);
            }
        }

        protected bool uploadAImage()
        {
            lblMess.Text = "";
            if (SingleUpload.HasFile)
            {
                bool check = false;
                string[] end = { ".gif", ".jpeg", ".png", ".bmp", ".wmf", ".jpg", ".GIF", ".JPEG", ".PNG", ".BMP", ".WMF", "JPG" };
                foreach (string a in end)
                {
                    if (SingleUpload.FileName.EndsWith(a))
                    {
                        check = true;
                    }
                }
                if (check)
                {
                    SingleUpload.SaveAs(Server.MapPath("..\\Single Upload") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + SingleUpload.FileName);
                    return true;
                }
                else
                {
                    lblMess.Text = "The upload file is not the image file. Please upload a image file";
                    return false;
                }
            }
            else
            {
                Utilities.Show("You have to choose a picture to finish your upload!");
                lblMess.Text = "Please upload the image of the advertisement.";
                return false;
            }
        }

        protected void getCountries()
        {
            DataTable dt = new DataTable();
            dt = countriesDalObj.getCountriesData();
            ddlCountry.DataSource = dt;
            ddlCountry.DataTextField = "CountryName";
            ddlCountry.DataValueField = "CountryId";
            ddlCountry.DataBind();
        }

        protected void getRegions(Region regObj)
        {
            DataTable dt = new DataTable();
            dt = regionDalObj.GetRegionsByCountryId(regObj);
            ddlRegion.DataSource = dt;
            ddlRegion.DataValueField = "RegionId";
            ddlRegion.DataTextField = "RegionName";
            ddlRegion.DataBind();
        }

        protected void getCities(City cityObj)
        {
            DataTable dt = new DataTable();
            dt = citiesDalObj.GetCitiesByRegionId(cityObj);
            ddlCity.DataSource = dt;
            ddlCity.DataValueField = "CityId";
            ddlCity.DataTextField = "CityName";
            ddlCity.DataBind();
        }

        protected void getDistricts(District districtObj)
        {
            DataTable dt = new DataTable();
            dt = districtsDalObj.GetDistrictByCityId(districtObj);
            ddlDistrict.DataSource = dt;
            ddlDistrict.DataValueField = "DistrictId";
            ddlDistrict.DataTextField = "DistrictName";
            ddlDistrict.DataBind();
        }

        public void getCategories()
        {
            DataTable dt = new DataTable();
            dt = cateDalObj.GetCategoriessData();
            ddlCategory.DataSource = dt;
            ddlCategory.DataValueField = "CategoryId";
            ddlCategory.DataTextField = "CategoryName";
            ddlCategory.DataBind();
        }

        protected void GetPackages()
        {
            DataTable dt = new DataTable();
            dt = parkDalObj.getPackagesData();
            ddlPackages.DataSource = dt;
            ddlPackages.DataValueField = "PackageId";
            ddlPackages.DataTextField = "PackageName";
            ddlPackages.DataBind();
        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            Region regObj = new Region();
            regObj.CountryId = int.Parse(ddlCountry.SelectedValue);
            getRegions(regObj);
            ddlRegion.Items.Insert(0, "--Select Region--");
            if (ddlRegion.Items.Count > 1)
            {
                ddlRegion.Enabled = true;
            }
            else
            {
                ddlRegion.Enabled = false;
            }
        }

        protected void ddlRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            City cityObj = new City();
            cityObj.RegionId = int.Parse(ddlRegion.SelectedValue);
            getCities(cityObj);
            ddlCity.Items.Insert(0, "--Select City--");
            if (ddlCity.Items.Count > 1)
            {
                ddlCity.Enabled = true;
            }
            else
            {
                ddlCity.Enabled = false;
            }
        }


        protected void UploadMultiFile()
        {
            
            if (MultiUpload.HasFile)
            {
                //string count = "";
                int iUploadedCnt = 0;
                int iFailedCnt = 0;
                HttpFileCollection hfc = Request.Files;
                lblFileList.Text = "You select <b>" + hfc.Count + "</b> file(s)";
                strUrl = new string[hfc.Count];
                int numberImg = NumberImages();
                if (hfc.Count <= (numberImg + 1))    // NUMBER FILES RESTRICTION.
                {
                    n = hfc.Count;
                    
                    for (int i = 0; i <= hfc.Count - 1; i++)
                    {
                        HttpPostedFile hpf = hfc[i];
                        if (hpf.ContentLength > 0)
                        {
                            if (!File.Exists(Server.MapPath("Images Upload\\") + Path.GetFileName(hpf.FileName)))
                            {
                                DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("Images Upload\\"));
                                string sFileName = Path.GetFileName(hpf.FileName);
                                string sFileExt = Path.GetExtension(hpf.FileName);

                                // CHECK FOR DUPLICATE FILES.
                                FileInfo[] objFI = objDir.GetFiles(sFileName.Replace(sFileExt, "") + ".*");

                                if (objFI.Length > 0)
                                {
                                    // CHECK IF FILE WITH THE SAME NAME EXISTS (IGNORING THE EXTENTIONS).
                                    foreach (FileInfo file in objFI)
                                    {
                                        string sFileName1 = objFI[0].Name;
                                        string sFileExt1 = Path.GetExtension(objFI[0].Name);

                                        if (sFileName1.Replace(sFileExt1, "") == sFileName.Replace(sFileExt, ""))
                                        {
                                            iFailedCnt += 1;        // NOT ALLOWING DUPLICATE.
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    // SAVE THE FILE IN A FOLDER.
                                    hpf.SaveAs(Server.MapPath("Images Upload\\") + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(hpf.FileName));
                                    iUploadedCnt += 1;
                                    strUrl[i] = "Images Upload" + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(hpf.FileName);
                                    //adsImageObj.ImageUrl = adsImageObj.ImageUrl + "#" + "Images Upload" + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(hpf.FileName);
                                    string FileToDelete = Server.MapPath("Images Upload\\") + DateTime.Now.ToString("yyyyMMddHHmmss") + SingleUpload.FileName;
                                    //count = "Images Upload" + "\\" + SingleUpload.FileName;
                                    File.Delete(FileToDelete);
                                }
                            }
                        }
                    }

                    //adsImageObj.ImageUrl = adsImageObj.ImageUrl.Remove(0, count.Replace(" ", "a").Length+15);
                    lblUploadStatus.Text = "<b>" + iUploadedCnt + "</b> file(s) Uploaded.";
                    lblFailedStatus.Text = "<b>" + iFailedCnt + "</b> duplicate file(s) could not be uploaded.";
                }
                else
                {
                    lblUploadStatus.Text = "You are only uploaded less than " + numImage + " images";
                    return;
                }
            }
            else lblUploadStatus.Text = "No files selected.";
        }

        protected int GetCurrentSession() {

            return Convert.ToInt16(Session["adminId"]);
        }

        private int GetDurationOfPackage() {
            DataTable dt = new DataTable();
            Package pObj = new Package();
            pObj.PackageId = int.Parse(ddlPackages.SelectedValue);
            dt = parkDalObj.GetPackageById(pObj);
            
            return int.Parse(dt.Rows[0]["Duration"].ToString());
        }

        private DateTime GetCurrentDate() {
            return DateTime.Now;
        }

        protected void ddlCity_SelectedIndexChanged1(object sender, EventArgs e)
        {
            District districtObj = new District();
            districtObj.CityId = 1;
            getDistricts(districtObj);
            ddlDistrict.Items.Insert(0, "--Select District--");
            if (ddlDistrict.Items.Count > 1)
            {
                ddlDistrict.Enabled = true;
            }
            else
            {
                ddlDistrict.Enabled = false;
            }
        }

        public void ProcessImagePriview(HttpContext context) {
            if ((context.Session["ImageBytes"]) != null)
            {
                byte[] image = (byte[])(context.Session["ImageBytes"]);
                context.Response.ContentType = "image/JPEG";
                context.Response.BinaryWrite(image);
            } 
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCategory.SelectedItem.Text == "Land")
            {
                HideDivForLand();
            }
            else
            {
                ShowDivForHouseAndVillage();
            }
        }

        protected void ddlPackages_SelectedIndexChanged(object sender, EventArgs e)
        {
            //DataTable dt = new DataTable();
            //Package packObj = new Package();
            //packObj.PackageId = Convert.ToInt16(ddlPackages.SelectedValue);
            //dt = parkDalObj.GetPackageById(packObj);
            //numImage = Convert.ToInt16(dt.Rows[0]["NumOfImg"].ToString());
        }

        private int NumberImages() {
            DataTable dt = new DataTable();
            Package packObj = new Package();
            packObj.PackageId = Convert.ToInt16(ddlPackages.SelectedValue);
            dt = parkDalObj.GetPackageById(packObj);
            numImage = Convert.ToInt16(dt.Rows[0]["NumOfImg"].ToString());
            return numImage;
        }

        private void InsertToSubscription() {
            DataTable dt = new DataTable();
            Subcription subObj = new Subcription();
            subObj.SubDate = GetCurrentDate().ToString("MM-dd-yyyy");
            subObj.UserId = GetCurrentSession();
            subObj.PackageId = int.Parse(ddlPackages.SelectedValue);
            if (ddlPackages.SelectedItem.Text == "Free")
            {
                subObj.IsPaid = true;
            }
            else {
                subObj.IsPaid = false;
            }
            SubcriptionDAL subDAL = new SubcriptionDAL();
            dt = subDAL.InsertToSubcription(subObj);
        }
    }
}